<?php

namespace app\admin\controller\xilumarket\order;

use think\Db;
use think\Hook;
use think\Loader;
use think\Validate;
use think\Exception;
use app\common\model\Config;
use function fast\array_get;
use think\exception\PDOException;
use app\common\controller\Backend;
use think\exception\ValidateException;
use app\common\model\xilumarket\ChatSession;
use app\admin\model\xilumarket\order\OrderDelivery;

/**
 * 商品订单
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\xilumarket\order\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\xilumarket\order\Order;
        $this->view->assign("payTypeList", $this->model->getPayTypeList());
        $this->view->assign("editAddressStatusList", $this->model->getEditAddressStatusList());
        $this->view->assign("freightTypeList", $this->model->getFreightTypeList());
        $this->view->assign("payStatusList", $this->model->getPayStatusList());
        $this->view->assign("freightStatusList", $this->model->getFreightStatusList());
        $this->view->assign("receiptStatusList", $this->model->getReceiptStatusList());
        $this->view->assign("commentStatusList", $this->model->getCommentStatusList());
        $this->view->assign("refundStatusList", $this->model->getRefundStatusList());
        $this->view->assign("orderStatusList", $this->model->getOrderStatusList());
    }

    public function set($ids) {
        if($this->request->isPost()){
            Db::startTrans();
            try{
                $data = $this->request->post();
                $order = $this->model->with(['delivery', 'orderProduct'])->find($ids);
                if(!empty($order->delivery->id)) {
                    return $this->error('该订单已分配骑手');
                }
                $config = \app\common\model\Config::get(['name' => 'delivery_fee']);
                $delivery = OrderDelivery::create([
                    'user_id' => $data['row']['user_id'], 
                    'order_id' => $ids, 
                    'fee' => $config['value'], 
                    'status' => 1
                ]);
                
                $chat = new \addons\xilumarket\chatprograms\library\Chat();
                foreach($order->orderProduct as $product){
                    $session = ChatSession::create([
                        'product_id'    => $product->product_id,
                        'send_user_id'  => $order->user_id,
                        'receive_user_id' => $product->product->user_id,
                        'delivery_user_id' => $data['row']['user_id'],
                    ]);
                    create_ws_group($order->user_id, $session->id);
                    create_ws_group($product->product->user_id, $session->id);
                    create_ws_group($data['row']['user_id'], $session->id);
                }
                $order->freight_status = 1;
                $order->save();
                Db::commit();
                send_to_ws($chat->say($data['row']['user_id'], [
                    'type' => 'say',
                    'receive_user_id' => $order->user_id,
                    'content'   => "你好，该订单由我进行配送。",
                    'chat_type' => 1,
                    'product_id' => $product->product_id,
                ], $session->id), 'user_'.$order->user_id, 'session_'.$session->id);
            }catch(\Throwable $e) {
                Db::rollback();
                return $this->error($e->getMessage());
            }
            return $this->success();
        }
        return $this->fetch();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user'=>function($query){
                    $query->withField(['id','nickname','username','avatar']);
                },
                'delivery',
//                ,'orderProduct'=>function($query){
//                    $query->field(['id','order_id','product_name','image','product_price','sum_price']);
//                },'orderAddress'
                ])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if($row->state != '1') {
                    $this->error('订单当前不可发货');
                }
                if(!$params['express_company_id'] || !$params['express_no']){
                    $this->error('快递公司或快递单号未填写');
                }
                $company = \app\admin\model\xilumarket\order\ExpressCompany::get($params['express_company_id']);
                if(!$company){
                    $this->error('快递公司不存在');
                }
                $params['express_name'] = $company->name;
                $params['express_code'] = $company->code;
                $params['freight_status'] = '1';
                $params['freighttime'] = time();
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    //发货消息
                    $order =\app\common\model\xilumarket\Order::get($row->id);
                    Hook::listen("xilumarket_order_freight",$order);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->view->assign('companys',\app\admin\model\xilumarket\order\ExpressCompany::column('id,name'));
        $this->assignconfig('order_id',$ids);
        return $this->view->fetch();
    }

    /**
     * 修改备注
     * @param null $ids
     */
    public function note_edit($ids=NULL){
        $param = $this->request->param('');

        if(!trim($param['admin_note'])){
            $this->error('备注不得为空');
        }
        $row = $this->model->get($ids);
        $row['admin_note'] = trim($param['admin_note']);

        $row->save();
        $this->success('保存成功');
    }


    //修改收货信息
    public function address_edit(){
        $params = $this->request->param('');

        $row = $this->model->get(array_get($params,'order_id'));
        if($row->state != 1){
            $this->error('只支持待发货订单修改');
        }

        $validator = Validate::make([
            'name|收货人' => ['require'],
            'mobile|手机号' => ['require'],
            'province_id|收货地址' => ['require'],
            'city_id|收货地址' => ['require'],
            'region_id|收货地址' => ['require'],
            'address_detail|详细地址' => ['require']
        ]);
        if(!$validator->check($params)) {
            $this->error($validator->getError());
        }
        $address = $row->order_address;
        $address->save($params);
        $this->success('修改成功');
    }



    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset/d", 0);
        $limit = $this->request->get("limit/d", 999999);
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
        if (!empty($this->model) && $this->relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }
            if($k=='state'){
                switch ($v){
                    case '-1':
                        $where[] = ['order_status','=','2'];
                        break;
                    case '0':
                        #待付款
                        $where[] = ['pay_status','=','0'];
                        $where[] = ['freight_status','=','0'];
                        $where[] = ['receipt_status','=','0'];
                        $where[] = ['order_status','=','1'];
                        break;
                    case '1':
                        #待发货
                        $where[] = ['pay_status','=','1'];
                        $where[] = ['freight_status','=','0'];
                        $where[] = ['receipt_status','=','0'];
                        $where[] = ['refund_status','in',['0','1']];
                        $where[] = ['order_status','=','1'];
                        break;
                    case '2':
                        #待收货
                        $where[] = ['pay_status','=','1'];
                        $where[] = ['freight_status','=','1'];
                        $where[] = ['receipt_status','=','0'];
                        $where[] = ['refund_status','in',['0','1']];
                        $where[] = ['order_status','=','1'];
                        break;
                    case '3':
                        //待评价
                        $where[] = ['pay_status','=','1'];
                        $where[] = ['freight_status','=','1'];
                        $where[] = ['receipt_status','=','1'];
                        $where[] = ['comment_status','=','0'];
                        $where[] = ['refund_status','in',['0','1']];
                        $where[] = ['order_status','=','1'];
                        break;
                    case '4':
                        //已完成
                        //$where[] = ['pay_status','=','1'];
                        //$where[] = ['freight_status','=','1'];
                        //$where[] = ['receipt_status','=','1'];
                        $where[] = ['refund_status','in',['0','1']];
                        $where[] = ['order_status','=','3'];
                        break;
                    case '5':
                        //部分退款
                        $where[] = ['pay_status','=','1'];
                        $where[] = ['freight_status','=','1'];
                        $where[] = ['receipt_status','=','1'];
                        $where[] = ['refund_status','=','1'];
                        break;
                    case '6':
                        //全部退款
                        $where[] = ['pay_status','=','1'];
                        $where[] = ['freight_status','=','1'];
                        $where[] = ['receipt_status','=','1'];
                        $where[] = ['refund_status','=','2'];
                        break;
                }
                continue;
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr, function($v){
                            return $v != '' && $v !== false && $v !== null;
                        })) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }

}
